import { useDrag, useDrop } from 'react-dnd';

import { useRef, useState, useEffect, useCallback } from 'react';

const DragItem = function ({ container, index, swap }) {
  const ref = useRef(null);
  const [, drag] = useDrag({
    type: 'box',
    item: { id: container },
  });
  const [, drop] = useDrop(() => {
    return {
      accept: 'box',
      drop(item) {
        swap(index, item.id);
      },
    };
  });
  useEffect(() => {
    drop(drag(ref));
  }, [ref, drag, drop]);
  return (
    <li ref={ref}>
      container：{container} | index：{index}
    </li>
  );
};

export default function Root() {
  const [boxes, setBoxes] = useState([0, 1, 2, 3, 4, 5, 6, 7, 8]);
  const dropRef = useRef(null);

  const swap = useCallback((index1, index2) => {
    setBoxes((prevBoxes) => {
      const newBoxes = [...prevBoxes];
      const tmp = newBoxes[index1];
      newBoxes[index1] = newBoxes[index2];
      newBoxes[index2] = tmp;
      return newBoxes;
    });
  }, []); // 无需依赖boxes

  return (
    <div ref={dropRef} style={{ width: 500, height: '100%', border: '1px solid black' }}>
      {boxes.map((item, index) => (
        <DragItem container={item} index={index} swap={swap} key={index} />
      ))}
    </div>
  );
}
